package systeminfo

import (
	"fmt"
	"golang.org/x/sys/windows"
	"strings"
	"unicode/utf16"
)

func DiskUsage(path string) (disk Hdd, err error) {
	var freeBytesAvailable uint64
	var totalNumberOfBytes uint64
	var totalNumberOfFreeBytes uint64
	err = windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr(path),
		&freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)
	if err != nil {
		return disk, err
	}
	disk.Path = path
	disk.All = fmt.Sprintf("%.2f", float64(totalNumberOfBytes)/1024/1024/1024)
	disk.Free = fmt.Sprintf("%.2f", float64(totalNumberOfFreeBytes)/1024/1024/1024)
	disk.Used = fmt.Sprintf("%.2f", float64(totalNumberOfBytes-totalNumberOfFreeBytes)/1024/1024/1024)

	return disk, nil
}

func GetDriveLetters() ([]string, error) {
	n, e := windows.GetLogicalDriveStrings(0, nil)
	if e != nil {
		return nil, e
	}
	a := make([]uint16, n)
	_, err := windows.GetLogicalDriveStrings(n, &a[0])
	if err != nil {
		return []string{}, err
	}
	s := string(utf16.Decode(a))
	return strings.Split(strings.TrimRight(s, "\x00"), "\x00"), nil
}

func GetHDDStatus() (status []Hdd) {
	drives, err := GetDriveLetters()
	if err != nil {
		fmt.Println("Failed to get drive letters:", err)
		return []Hdd{}
	}
	//log.Println("drive list: ", drives)
	status = []Hdd{}
	for _, drive := range drives {
		//log.Println("drive: ", drive)
		disk, err := DiskUsage(drive)
		if err != nil {
			fmt.Printf("Failed to get disk usage for drive %s: %v\n", drive, err)
			continue
		}
		status = append(status, disk)
	}
	return
}
